----------------------------------------------------------------------------------
-- Company:        RIT
-- Engineer:       Sam Skalicky
-- 
-- Create Date:    17:49:05 12/11/2009 
-- Design Name:    MSD P10662
-- Module Name:    Device - Behavioral 
-- Project Name:   Inout
-- Target Devices: Spartan 6 LXT
-- Tool versions:  QuestaSim-64 6.4c
-- Description:    This a bi-directional I2C/Two-wire port implementation in VHDL
--
-- Notes: Data is the bi-directional port, Clk is typeset as an inout in the idea that
-- the clock could be generated to this port (Master device) or recieved from this port
-- in the case of a Slave device. However it is not meant to be a bi-directional port
--
-- Dependencies:   None
--
-- Revision: 1.0
-- Revision 0.01 - File Created
-- Additional Comments: 
--
----------------------------------------------------------------------------------
library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.STD_LOGIC_ARITH.ALL;
use IEEE.STD_LOGIC_UNSIGNED.ALL;

entity I2CmasterDemo2 is
    Port ( FPGA_Clk : IN std_logic;
		     I2C_Clk : out std_logic;
    		  I2C_Data : inout std_logic;
			  SW : IN std_logic_vector(3 downto 0));
end I2CmasterDemo2;

architecture Behavioral of I2CmasterDemo2 is

  component I2Cmaster is
    Generic (register_data_width : natural;
             register_id_width : natural);
    Port ( PS2_Data : inout  STD_LOGIC;
           PS2_Clk : in  STD_LOGIC;
			  FPGAClk : in std_logic;
			  I2C_Clk_out : out std_logic;
           Send : in std_logic;
           Instruction : in std_logic_vector(7 downto 0);
           register_id : in std_logic_vector(register_id_width-1 downto 0);
           Data : inout std_logic_vector(register_data_width-1 downto 0)); 
  end component;
  
  component Clk_100kHz is
	  Port(FPGA_Clk : IN std_logic;
		     I2C_Clk : out std_logic);
  end component;

  signal si2c_clk,sfpga_clk : std_logic:='0';
  signal si2c_data : std_logic:='1';
  signal address_rw : std_logic_vector(7 downto 0):="00001101";   -- XXXXXXX Z (7 bits address) + (1 bit R(0)/W(1))
  signal address_out : std_logic_vector(7 downto 0):="10111101";  --register address
  signal data : std_logic_vector(7 downto 0):="11011010"; --data
  signal sSW : std_logic_vector(3 downto 0):=X"0";
  signal i2c_clk_out : std_logic:='1';
begin
  
  CLK: Clk_100kHz port map(sfpga_clk,si2c_clk);

  UUT: I2Cmaster 
  generic map(8,8)
  port map(si2c_data,si2c_clk,sfpga_clk,i2c_clk_out,sSW(3),address_rw,address_out,data);
  
  sfpga_clk<=FPGA_clk;
  I2C_Clk<=i2c_clk_out;
  I2C_Data<=si2c_data;
	
  process(SW,si2c_clk)
  begin
    if rising_edge(si2c_clk) then
	   sSW(1 downto 0)<=sSW(0) & SW(3);
		
		if sSW(1 downto 0) = "00" and sSW(2) = '1' then
		  sSW(3)<='0';
		  sSW(2)<='0';
		elsif sSW(1 downto 0) = "11" and sSW(2) = '0' then
		  sSW(2)<='1';
		  sSW(3)<='1';
		else
		  sSW(3)<='0';
		end if;
	 end if;
  end process;
  
end Behavioral;